import React, { useEffect } from 'react';
import { Form, Input, Select, TreeSelect } from 'antd';

import { ProBox, type WrappedComponentProps } from "@yaf/pro-ui";
import { getEnv } from '@/constants';

import { useDataAuth } from './useDataAuth';

interface DataAuthProps extends WrappedComponentProps {
  roleId: number;
  dataScope: number;
  roleName: string;
  fetchList: () => void;
}

const DataAuth: React.FC<DataAuthProps> = ({ modalControl, roleId, dataScope, roleName, fetchList }) => {
  const { roleDataScopeType, roleDataScopeTypeList } = getEnv().globalConfig;

  const [form] = Form.useForm();
  const { loading, deptTree, selectedDataScope, setSelectedDataScope, selectedDeptIds, updateDataScope } = useDataAuth(roleId, dataScope)

  useEffect(() => {
    modalControl.registerOk(handleSubmit);
  });

  const handleSubmit = () => {
    form.validateFields().then((values) => {
      updateDataScope(values, () => {
        fetchList();
        modalControl.close()
      }, () => modalControl.hideSaving())
    }).catch(() => modalControl.hideSaving())
  }

  return <ProBox loading={loading}>
    <Form form={form} initialValues={{ dataScope: selectedDataScope, deptIds: selectedDeptIds }}>
      <Form.Item label="角色名称">
        <Input value={roleName} disabled />
      </Form.Item>
      <Form.Item
        label="权限范围"
        name="dataScope"
      >
        <Select onChange={(value) => setSelectedDataScope(value)} options={roleDataScopeTypeList} />
      </Form.Item>

      {roleDataScopeType.custom == selectedDataScope && <Form.Item
        label="组织结构"
        name="deptIds"
      >
        <TreeSelect treeData={deptTree} treeCheckable={true} maxTagCount="responsive" />
      </Form.Item>}
    </Form>
  </ProBox>
}

export default DataAuth


//
// interface TreeFormItemProps{
//     treeData: any,
//     value?: (number | string)[];
//     onChange?: (keys: (number | string)[]) => void;
// }
//
// const TreeFormItem: React.FC<TreeFormItemProps> = ({value, onChange, treeData}) => {
//
//
//     return <Tree
//         checkable
//         checkStrictly
//         checkedKeys={value}
//         onCheck={(e, d) => {
//             console.log("e->",e);
//             const keys = e.checked;
//             // const parentKeys = d.node.parentKey;
//             // if (d.checked) {
//             //     existOrPush(keys, parentKeys);
//             // }
//             // if (d.node.children && d.node.children.length > 0) {
//             //
//             //     const childrenKeys = recursion(d.node.children);
//             //
//             //     if (d.checked) {
//             //         existOrPush(keys, childrenKeys);
//             //     } else {
//             //         unExistOrPop(keys, childrenKeys)
//             //     }
//             // }
//             onChange(keys)
//         }}
//         treeData={treeData}
//     />
// }
//
